package com.qubuyer.core.framework

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import com.qubuyer.core.anno.AutoInject
import com.qubuyer.core.ext.hideHttpRequestProgressDialog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import java.lang.reflect.Field
import kotlin.coroutines.CoroutineContext

/**
 * Author: linwg
 * Description:基类
 */
open class BaseViewModel(private val job: Job = Job()) : ViewModel(), CoroutineScope {
    var lifecycleOwner: LifecycleOwner? = null
        set(value) {
            field = value
            autoInjectModel(this.javaClass)
        }

    private fun autoInjectModel(clazz: Class<*>) {
        if (lifecycleOwner == null) {
            return
        }
        var fields: Array<Field> = clazz.fields
        autoInjectField(fields)
        fields = clazz.declaredFields
        autoInjectField(fields)
        val superclass: Class<*>? = clazz.superclass
        if (superclass != null) {
            autoInjectModel(superclass)
        }
    }

    @Throws(IllegalAccessException::class)
    private fun autoInjectField(fields: Array<Field>) {
        for (field in fields) {
            val annotation: AutoInject? = field.getAnnotation(AutoInject::class.java)
            if (annotation != null) {
                field.isAccessible = true
                val model = field.get(this)
                if (model is BaseModel) {
                    model.init(lifecycleOwner!!)
                }
            }
        }
    }

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun onCleared() {
        super.onCleared()
        job.cancel()
        lifecycleOwner?.hideHttpRequestProgressDialog()
        lifecycleOwner = null
    }
}